{% extends "base.html" %}

{% block content %}
<head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <style>
        .cursor-move {
            cursor: move;
        }
        .sortable-ghost {
            opacity: 0.5;
        }
    </style>
</head>

<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="mb-0">创建表单</h4>
        <div>
            <button type="button" class="btn btn-sm btn-outline-secondary me-2" onclick="window.history.back()">返回</button>
            <button type="button" class="btn btn-sm btn-outline-primary" onclick="previewForm()">预览</button>
        </div>
    </div>
    <form id="formBuilder" method="POST">
        <div class="card mb-4">
            <div class="card-body">
                <div class="mb-3">
                    <label for="title" class="form-label">表单标题</label>
                    <input type="text" class="form-control form-control-sm" id="title" name="title" required 
                           placeholder="请输入表单标题" maxlength="100">
                    <div class="form-text">标题长度不超过100个字符</div>
                </div>
                <div class="mb-3">
                    <label for="description" class="form-label">表单描述</label>
                    <textarea class="form-control form-control-sm" id="description" name="description" rows="3"
                              placeholder="请输入表单说明，可以包含填写须知、注意事项等"></textarea>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="allowMultiSubmit" name="allowMultiSubmit" checked>
                            <label class="form-check-label" for="allowMultiSubmit">允许多次提交</label>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="showProgress" name="showProgress" checked>
                            <label class="form-check-label" for="showProgress">显示填写进度</label>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header py-2">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <span class="me-2">表单字段</span>
                        <small class="text-muted">已添加 <span id="fieldCount">0</span> 个字段</small>
                    </div>
                    <button type="button" class="btn btn-sm btn-primary" onclick="addField()">添加字段</button>
                </div>
            </div>
            <div class="card-body">
                <div class="alert alert-info mb-3">
                    <strong>提示：</strong>
                    <ul class="mb-0">
                        <li>拖动字段可以调整顺序</li>
                        <li>必填字段会在标签后显示红色星号</li>
                        <li>建议先规划好表单结构再开始创建</li>
                    </ul>
                </div>
                <div id="fields"></div>
                <div id="emptyFields" class="text-center text-muted py-4">
                    <i class="bi bi-plus-circle" style="font-size: 2rem;"></i>
                    <p class="mt-2">点��"添加字段"开始创建表单</p>
                </div>
            </div>
        </div>

        <div class="text-end">
            <span class="text-muted me-2">创建后可以在表单列表中管理和预览</span>
            <button type="submit" class="btn btn-sm btn-primary">创建表单</button>
        </div>
    </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.14.0/Sortable.min.js"></script>

<script>
// 初始化拖拽排序
new Sortable(document.getElementById('fields'), {
    animation: 150,
    handle: '.card-header',  // 只能通过卡片头部拖动
    ghostClass: 'bg-light'   // 拖动时的样式
});

let fieldCount = 0;

function addField() {
    const fieldHtml = `
        <div class="card mb-3" id="field${fieldCount}">
            <div class="card-header cursor-move">
                <i class="bi bi-grip-vertical me-2"></i>
                字段 #${fieldCount + 1}
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label class="form-label">字段标签</label>
                            <input type="text" class="form-control field-label" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label class="form-label">字段类型</label>
                            <select class="form-select field-type" required onchange="toggleFieldSettings(this)">
                                <option value="text">文本</option>
                                <option value="number">数字</option>
                                <option value="textarea">多行文本</option>
                                <option value="date">日期</option>
                                <option value="time">时间</option>
                                <option value="idcard">身份证号</option>
                                <option value="select">下拉选择</option>
                                <option value="radio">单选</option>
                                <option value="checkbox">多选</option>
                            </select>
                        </div>
                        <div class="options-container" style="display: none;">
                            <div class="mb-3">
                                <label class="form-label">选项列表</label>
                                <div class="options-list">
                                    <div class="input-group mb-2">
                                        <input type="text" class="form-control form-control-sm field-option" placeholder="选项值">
                                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeOption(this)">删除</button>
                                    </div>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-primary mt-1" onclick="addOption(this)">添加选项</button>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3 d-flex align-items-end">
                            <div class="form-check me-3">
                                <input class="form-check-input field-required" type="checkbox" id="required${fieldCount}" checked>
                                <label class="form-check-label" for="required${fieldCount}">必填</label>
                            </div>
                            <button type="button" class="btn btn-danger btn-sm ms-auto" onclick="removeField(${fieldCount})">删除</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    document.getElementById('fields').insertAdjacentHTML('beforeend', fieldHtml);
    fieldCount++;
    updateFieldCount();
}

function removeField(id) {
    document.getElementById(`field${id}`).remove();
    updateFieldCount();
}

document.getElementById('formBuilder').onsubmit = async function(e) {
    e.preventDefault();
    
    // 验证表单标题
    const title = document.getElementById('title').value.trim();
    if (!title) {
        alert('请输入表单标题');
        return;
    }

    // 验证是否有字段
    if (document.querySelectorAll('#fields .card').length === 0) {
        alert('请至少添加一个字段');
        return;
    }

    const fields = [];
    document.querySelectorAll('#fields .card').forEach((fieldCard, index) => {
        const fieldType = fieldCard.querySelector('.field-type').value;
        const field = {
            name: `field${index}`,
            label: fieldCard.querySelector('.field-label').value,
            type: fieldType,
            required: fieldCard.querySelector('.field-required').checked
        };

        // 如果是需要选项的字段类型，添加选项
        if (['select', 'radio', 'checkbox'].includes(fieldType)) {
            const options = Array.from(fieldCard.querySelectorAll('.field-option'))
                .map(input => input.value.trim())
                .filter(value => value !== '');
            
            if (options.length === 0) {
                alert(`请为"${field.label}"添加至少一个选项`);
                return;
            }
            
            field.options = options;
        }

        fields.push(field);
    });

    // 如果验证过程中有返回，则停止提交
    if (fields.length !== document.querySelectorAll('#fields .card').length) {
        return;
    }

    const data = {
        title: title,
        description: document.getElementById('description').value.trim(),
        allow_multi_submit: document.getElementById('allowMultiSubmit').checked,
        fields: fields
    };

    // 显示加载状态
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 创建中...';

    try {
        const response = await fetch(this.action, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });

        const result = await response.json();
        if (response.ok && result.success) {
            alert('表单创建成功！');
            window.location.href = "{{ url_for('form_list') }}";
        } else {
            alert(result.message || '创建表单失败');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('创建表单失败，请重试');
    } finally {
        // 恢复按钮状态
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    }
};

// 添加一个默认字段
addField();

function previewForm() {
    const fields = [];
    document.querySelectorAll('#fields .card').forEach((fieldCard, index) => {
        const fieldType = fieldCard.querySelector('.field-type').value;
        const field = {
            name: `field${index}`,
            label: fieldCard.querySelector('.field-label').value,
            type: fieldType,
            required: fieldCard.querySelector('.field-required').checked
        };

        if (['select', 'radio', 'checkbox'].includes(fieldType)) {
            const options = Array.from(fieldCard.querySelectorAll('.field-option'))
                .map(input => input.value.trim())
                .filter(value => value !== '');
            field.options = options;
        }

        fields.push(field);
    });

    const previewHtml = `
        <div class="modal fade" id="previewModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">${document.getElementById('title').value}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <p class="mb-4">${document.getElementById('description').value}</p>
                        <form>
                            ${fields.map(field => generateFieldHtml(field)).join('')}
                        </form>
                    </div>
                </div>
            </div>
        </div>
    `;

    // 移除旧的预览模态框
    const oldModal = document.getElementById('previewModal');
    if (oldModal) oldModal.remove();

    // 添加新的预览模态框
    document.body.insertAdjacentHTML('beforeend', previewHtml);
    new bootstrap.Modal(document.getElementById('previewModal')).show();
}

function generateFieldHtml(field) {
    const requiredMark = field.required ? '<span class="text-danger">*</span>' : '';
    let html = `<div class="mb-3">
        <label class="form-label">${field.label}${requiredMark}</label>`;

    switch (field.type) {
        case 'text':
            html += `<input type="text" class="form-control form-control-sm" ${field.required ? 'required' : ''}>`;
            break;
        case 'number':
            html += `<input type="number" class="form-control form-control-sm" ${field.required ? 'required' : ''}>`;
            break;
        case 'idcard':
            html += `<input type="text" class="form-control form-control-sm" 
                    pattern="[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\\d{3}[0-9Xx]"
                    oninput="validateIdCard(this)" 
                    ${field.required ? 'required' : ''}>
                    <div class="invalid-feedback"></div>`;
            break;
        case 'textarea':
            html += `<textarea class="form-control form-control-sm" rows="3" ${field.required ? 'required' : ''}></textarea>`;
            break;
        case 'date':
            html += `<input type="date" class="form-control form-control-sm" ${field.required ? 'required' : ''}>`;
            break;
        case 'time':
            html += `<input type="time" class="form-control form-control-sm" ${field.required ? 'required' : ''}>`;
            break;
        case 'select':
            html += `<select class="form-select form-select-sm" ${field.required ? 'required' : ''}>
                <option value="">请选择</option>
                ${field.options?.map(opt => `<option value="${opt}">${opt}</option>`).join('') || ''}
            </select>`;
            break;
        case 'radio':
            html += (field.options || []).map(opt => `
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="${field.name}" value="${opt}" ${field.required ? 'required' : ''}>
                    <label class="form-check-label">${opt}</label>
                </div>`).join('');
            break;
        case 'checkbox':
            html += (field.options || []).map(opt => `
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="${field.name}" value="${opt}">
                    <label class="form-check-label">${opt}</label>
                </div>`).join('');
            break;
    }

    html += '</div>';
    return html;
}

function toggleFieldSettings(select) {
    const optionsContainer = select.closest('.col-md-4').querySelector('.options-container');
    const needsOptions = ['select', 'radio', 'checkbox'].includes(select.value);
    optionsContainer.style.display = needsOptions ? 'block' : 'none';
}

function validateIdCard(input) {
    const value = input.value;
    let errorMsg = '';

    // 基本格式验证
    if (!/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/.test(value)) {
        if (value.length !== 18) {
            errorMsg = '身份证号长度必须为18位';
        } else if (!/^[1-9]/.test(value)) {
            errorMsg = '身份证号码必须以数字1-9开头';
        } else if (!/^\d{17}[\dXx]$/.test(value)) {
            errorMsg = '身份证号码前17位必须为数字，最后一位必须为数字或X';
        } else {
            errorMsg = '身份证号码格式不正���';
        }
        input.setCustomValidity(errorMsg);
        input.classList.add('is-invalid');
        input.nextElementSibling.textContent = errorMsg;
        return;
    }

    // 日期验证
    const year = value.substr(6, 4);
    const month = value.substr(10, 2);
    const day = value.substr(12, 2);
    const date = new Date(year, month - 1, day);
    if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day) {
        errorMsg = '身份证号码中的出生日期无效';
        input.setCustomValidity(errorMsg);
        input.classList.add('is-invalid');
        input.nextElementSibling.textContent = errorMsg;
        return;
    }

    // 校验码验证
    const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const parity = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
    let sum = 0;
    
    for (let i = 0; i < 17; i++) {
        sum += parseInt(value[i]) * factor[i];
    }
    
    const check = parity[sum % 11];
    if (check.toLowerCase() !== value[17].toLowerCase()) {
        errorMsg = '身份证号校验码错误';
        input.setCustomValidity(errorMsg);
        input.classList.add('is-invalid');
        input.nextElementSibling.textContent = errorMsg;
        return;
    }

    // 验证通过
    input.setCustomValidity('');
    input.classList.remove('is-invalid');
}

// 更新字段计数
function updateFieldCount() {
    const count = document.querySelectorAll('#fields .card').length;
    document.getElementById('fieldCount').textContent = count;
    document.getElementById('emptyFields').style.display = count > 0 ? 'none' : 'block';
}

// 监听标题输入
document.getElementById('title').addEventListener('input', function() {
    const maxLength = 100;
    if (this.value.length > maxLength) {
        this.value = this.value.slice(0, maxLength);
    }
    const remaining = maxLength - this.value.length;
    this.nextElementSibling.textContent = `还可以输入${remaining}个字符`;
});

function addOption(btn) {
    const optionHtml = `
        <div class="input-group mb-2">
            <input type="text" class="form-control form-control-sm field-option" placeholder="选项值">
            <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeOption(this)">删除</button>
        </div>
    `;
    btn.previousElementSibling.insertAdjacentHTML('beforeend', optionHtml);
}

function removeOption(btn) {
    btn.closest('.input-group').remove();
}
</script>
{% endblock %} 